package com.llynic.designdemo.proxymode.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {
    private Object target;

    public Object newInstance(Object target){
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();

    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        doSomethingBefore();
        Object obj = null;
        //调用了父类的方法时,进行代理
        //obj = methodProxy.invokeSuper(o,objects);
        //通过method来代理被代理对象的方法
        if (null != o){
            obj = method.invoke(target, objects);
        }
        doSomethingAfter();
        return obj;
    }

    private void doSomethingBefore(){
        System.out.println("被代理对象方法执行前的增强");
    }

    private void doSomethingAfter(){
        System.out.println("被代理对象方法执行后的增强");
    }
}
